<template>
	<view class="container iden">
		<!-- <view class="title">身份认证</view> -->
		<view class="upload" @click="upload">
			<view class="box" v-if="!form.headPic">
				<img src="https://zrws-1327345771.cos.ap-shanghai.myqcloud.com/yanxue/camera.png" alt="" />
				<view class="des">点击上传</view>
			</view>
			<view class="box" v-else>
				<img class="head-pic" :src="form.headPic" alt="" />
			</view>
		</view>
		<view class="avator_text">你的头像</view>
		<u-form :label-style="labelStyle" :model="form" ref="uForm" label-position="top" class="form" :border-bottom="false">
			<u-form-item label="您的身份" class="identity" :border-bottom="false">
				<u-input v-model="form.type" v-show="false" />
				<view class="id">
					<view
						:class="{ item__checked: item.checked || isEdit }"
						class="id-item"
						v-for="(item, index) in ids"
						:key="index"
						@click="itemClick(item, index)"
					>
						<img :src="item.img" alt="" />
						<view class="id-text">{{ item.label }}</view>
					</view>
				</view>
			</u-form-item>
			<!-- 家长 -->
			<view v-if="currentIndex == 1">
				<u-form-item label="研学学员的姓名" :border-bottom="false">
					<view class="input-box">
						<u-input v-model="form.name" placeholder="输入研学学员的姓名" />
					</view>
				</u-form-item>
				<u-form-item label="研学学员的身份证号码" :border-bottom="false" v-if="!isEdit">
					<view class="input-box">
						<u-input v-model="form.cardNumber" placeholder="输入研学学员的身份证号码(18位)" />
					</view>
				</u-form-item>
			</view>
			<!-- 机构 -->
			<view v-else>
				<u-form-item label="机构名称" :border-bottom="false">
					<view class="input-box">
						<u-input v-model="form.name" placeholder="输入机构名称" />
					</view>
				</u-form-item>
				<block v-if="!isEdit">
					<u-form-item label="机构所在地" :border-bottom="false">
						<view class="input-box">
							<u-input v-model="form.addressInfo" placeholder="输入机构所在地" />
						</view>
					</u-form-item>
					<u-form-item label="机构人数" :border-bottom="false">
						<view class="input-box">
							<u-input v-model="form.institutionsAmount" placeholder="输入机构人数" />
						</view>
					</u-form-item>
					<u-form-item label="机构幼儿园学生人数" :border-bottom="false">
						<view class="input-box">
							<u-input v-model="form.kindergartenAmount" placeholder="输入机构幼儿园学生人数" />
						</view>
					</u-form-item>
					<u-form-item label="机构中学段学生人数" :border-bottom="false">
						<view class="input-box">
							<u-input v-model="form.middleAmount" placeholder="输入机构中学段学生人数" />
						</view>
					</u-form-item>
					<u-form-item label="机构课时费" :border-bottom="false">
						<view class="input-box">
							<u-input v-model="form.teachingPrice" placeholder="输入机构课时费" />
						</view>
					</u-form-item>
				</block>
			</view>
			<block v-if="!isEdit">
				<u-form-item label="联系方式" :border-bottom="false">
					<u-row gutter="16" style="width: 100%">
						<u-col span="8">
							<view class="input-box">
								<u-input v-model="form.mobile" placeholder="输入手机号码" />
							</view>
						</u-col>
						<u-col span="4">
							<view class="input-box btn" @click="getVerificationCode">
								{{ codeButtonText }}
							</view>
						</u-col>
					</u-row>
				</u-form-item>

				<view class="input-box">
					<u-input v-model="form.phoneCode" placeholder="输入你的验证码" />
				</view>
			</block>
			<view class="submit-btn" @click="submitForm">{{ !isEdit ? '立即登录' : '提交修改' }}</view>
		</u-form>
	</view>
</template>

<script>
// import group from "@/static/yanxue/group.png";
// import users from "@/static/yanxue/users.png";
import { userAuth, applyIdentityCheck, userInfoEdit } from '@/api/yanxue/user'
import Config from '@/config'
import { sendSmsCaptcha } from '@/api/captcha'
// import { setTimeout } from 'timers'
export default {
	data() {
		return {
			action: 'http://www.example.com/upload',
			fileList: [
				{
					url: 'http://pics.sc.chinaz.com/files/pic/pic9/201912/hpic1886.jpg'
				}
			],
			ids: [
				{
					label: '我是机构',
					checked: true,
					value: '1',
					img: ' https://zrws-1327345771.cos.ap-shanghai.myqcloud.com/yanxue/group.png'
				},
				{
					label: '我是家长',
					checked: false,
					value: '2',
					img: 'https://zrws-1327345771.cos.ap-shanghai.myqcloud.com/yanxue/users.png'
				}
			],
			form: {
				name: '',
				mobile: '',
				phoneCode: '',
				type: '',
				headPic: ''
			},
			currentIndex: 0,
			labelStyle: {
				color: '#000000',
				fontSize: '13px',
				fontWeight: '400',
				fontFamily: 'HarmonyOS Sans SC'
			},
			codeButtonText: '获取验证码',
			codeButtonDisabled: false,
			isEdit: false
		}
	},
	async onLoad(options) {
		console.log(options)
		if (options.edit) {
			// 修改信息
			uni.setNavigationBarTitle({
				title: '编辑信息'
			})
			let info = this.$store.state.user.userInfo
			this.isEdit = true
			this.form.name = info.nickName
			this.form.headPic = info.headPic
			if (info.userRole > 0) {
				this.ids.pop()
				this.currentIndex = 0
			} else {
				this.ids.shift()
				this.currentIndex = 1
			}
		}
		const code = await this.getCode()
		applyIdentityCheck({ code }).then(res => {
			if (res?.result?.code == 1) {
				uni.showToast({
					title: '您已申请认证，请等待审核',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 1000)
			}
		})
	},
	methods: {
		upload() {
			uni.chooseImage({
				success: chooseImageRes => {
					console.log('chooseImageRes1 :>> ', chooseImageRes)
					const tempFilePaths = chooseImageRes.tempFilePaths
					uni.uploadFile({
						url: 'https://yxapi.ziranweishi.com.cn/font/uploadByOss',
						filePath: tempFilePaths[0],
						name: 'file',
						success: uploadFileRes => {
							const res = JSON.parse(uploadFileRes.data)
							this.$set(this.form, 'headPic', res.data)
						}
					})
				},
				fail: err => {
					console.log('err :>> ', err)
				}
			})
		},
		itemClick(item, index) {
			this.ids.forEach(item => {
				item.checked = false
			})
			this.ids[index].checked = true
			this.form = {}
			this.form.type = this.ids[index].value
			this.currentIndex = index
		},
		async getVerificationCode() {
			if (this.codeButtonDisabled) return
			if (!this.form.mobile) {
				uni.showToast({
					title: '请输入手机号码',
					icon: 'none'
				})
				return
			}

			this.codeButtonDisabled = true
			this.codeButtonText = '发送中...'

			try {
				// 这里应该调用发送验证码的API
				const res = await sendSmsCaptcha({
					phone: this.form.mobile
				})
				if (res.status === 0) {
					let countdown = 60
					const timer = setInterval(() => {
						if (countdown > 0) {
							this.codeButtonText = `${countdown}秒后重试`
							countdown--
						} else {
							clearInterval(timer)
							this.codeButtonText = '获取验证码'
							this.codeButtonDisabled = false
						}
					}, 1000)
				} else {
					uni.showToast({
						title: res.msg || '发送失败',
						icon: 'none'
					})
					this.codeButtonText = '获取验证码'
					this.codeButtonDisabled = false
				}
			} catch (error) {
				console.error('发送验证码失败', error)
				uni.showToast({
					title: '发送失败，请重试',
					icon: 'none'
				})
				this.codeButtonText = '获取验证码'
				this.codeButtonDisabled = false
			}
		},
		validateForm() {
			// 表单验证逻辑
			if (!this.form.headPic) {
				uni.showToast({
					title: '请上传头像',
					icon: 'none'
				})
				return false
			}
			if (!this.form.name) {
				uni.showToast({
					title: this.currentIndex == 0 ? '请输入机构名称' : '请输入姓名',
					icon: 'none'
				})
				return false
			}
			if (!this.form.mobile || !this.validateMobile(this.form.mobile)) {
				uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				})
				return false
			}
			if (!this.form.phoneCode) {
				uni.showToast({
					title: '请输入验证码',
					icon: 'none'
				})
				return false
			}

			return true
		},
		// 校验手机号码
		validateMobile(mobile) {
			return /^1[3456789]\d{9}$/.test(mobile)
		},
		// 校验身份证号码
		validateCardNumber(cardNumber) {
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(cardNumber)
		},
		// 获取登录的code
		getCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: res => {
						resolve(res.code)
					},
					fail: reject
				})
			})
		},
		async submitForm() {
			if (this.isEdit) {
				this.editFunc()
				return
			}
			try {
				const code = await this.getCode()
				const authenticationRequest = {
					...this.form,
					code,
					type: this.currentIndex ? 0 : 1 // 1: 机构, 0: 家长
					// 根据用户类型添加其他字段
				}
				if (!this.validateForm()) {
					return
				}
				// 调用API
				const res = await userAuth(authenticationRequest)
				console.log('res :>> ', res)

				if (res.status === 0) {
					uni.showToast({
						title: '认证成功',
						icon: 'success'
					})
					// 处理成功后的逻辑，比如跳转页面
					setTimeout(() => {
						this.$navTo('pages/index/index')
					}, 1000)
				} else {
					uni.showToast({
						title: res.msg || '认证失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('表单提交失败', error)
				uni.showToast({
					title: '表单验证失败，请检查输入',
					icon: 'none'
				})
			}
		},
		editFunc() {
			if (!this.form.name) return uni.showToast({ title: '请输入名称', icon: 'none' })
			let obj = { headPic: this.form.headPic, nickName: this.form.name }
			userInfoEdit(obj).then(res => {
				uni.showToast({ title: '修改成功', icon: 'none' })
				setTimeout(() => {
					this.$navTo('pages/mine/index')
					console.log(123)
				}, 800)
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.iden .u-form-item {
	line-height: normal;
	padding: 0;
	margin-bottom: 30rpx;
}

.container {
	background: #ffffff;
	padding: 0 52rpx 200rpx;
	padding-top: 20rpx;
	text-align: center;

	.title {
		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 36rpx;
		color: #000000;
		margin: 0 auto 48rpx auto;
	}

	.avator_text {
		font-family: HarmonyOS Sans SC;
		font-size: 26rpx;
		color: #000000;
		margin-top: 16rpx;
		margin-bottom: 46rpx;
	}

	.upload {
		width: 196rpx;
		height: 196rpx;
		border-radius: 196rpx;
		background-color: #f6f6f6;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		overflow: hidden;

		.box {
			img {
				width: 50rpx;
				height: 44rpx;
			}

			.head-pic {
				width: 196rpx;
				height: 196rpx;
			}

			.des {
				font-family: HarmonyOS Sans SC;
				font-weight: 400;
				font-size: 20rpx;
				color: #000000;
				margin-top: 16rpx;
			}
		}
	}
}

.identity {
	border: none !important;
}

.id {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.id-item {
		width: 306rpx;
		height: 84rpx;
		border-radius: 84rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #e8e8e8;
		margin-right: 32rpx;
		cursor: pointer;

		img {
			width: 40rpx;
			height: 40rpx;
		}

		.id-text {
			margin-left: 16rpx;
			font-family: HarmonyOS Sans SC;
			font-weight: 500;
			font-size: 24rpx;
			color: #010101;
		}
	}

	.item__checked {
		background-color: #66ff2b;
	}
}

.input-box {
	width: 100%;
	height: 84rpx;
	border-radius: 84rpx;
	background-color: #e8e8e8;
	display: flex;
	// justify-content: center;
	align-items: center;
	padding: 7rpx 50rpx;

	u-input {
		width: 100%;
		height: 100%;
		border: none;
		background-color: #e8e8e8;
		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #010101;
	}
}

.btn {
	font-family: HarmonyOS Sans SC;
	font-weight: 500;
	font-size: 24rpx;
	color: #010101;
	line-height: 84rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0;
}

.submit-btn {
	width: 100%;
	height: 84rpx;
	border-radius: 84rpx;
	background-color: #66ff2b;
	font-family: HarmonyOS Sans SC;
	font-weight: 500;
	font-size: 24rpx;
	color: #010101;
	line-height: 84rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 40rpx;
}
</style>
